<template>
  <div class="look-company-container" :class="{ readonly: isReadOnly }">
    <el-card class="company-info-card">
      <template #header>
        <div class="card-header">
          <div>
            <span>企业信息</span
            ><el-button
              type="info"
              style="margin-left: 20px"
              @click="handleRefresh"
              :loading="refreshLoading"
              icon="Refresh"
              class="refresh-btn"
            >
              刷新
            </el-button>
          </div>
          <div class="operation-buttons">
            <el-button v-if="!isReadOnly" type="primary" @click="handleEditCompanyInfo">
              编辑
            </el-button>
            <template
              v-if="!isReadOnly && companyInfo.status >= 4 && !companyInfo.processId"
            >
              <!-- <el-button type="primary" @click="handleDepositToRent">押金转租金</el-button> -->
              <!-- <el-button type="success" @click="handleExpansion">扩租</el-button> -->
              <!-- <el-button type="warning" @click="handleReduction">缩租</el-button> -->
              <!-- <el-button type="primary" @click="handleRenewal">续租</el-button> -->
              <el-button
                type="primary"
                @click="handleChange"
                v-if="companyInfo.entryMode != '挂靠'"
                >合同变更</el-button
              >
              <el-button
                type="danger"
                @click="handleWithdrawal"
                v-if="companyInfo.entryMode != '挂靠'"
                >退租</el-button
              >
            </template>
            <template
              v-else-if="!isReadOnly && companyInfo.status >= 4 && companyInfo.processId"
            >
              <el-button type="warning" @click="handleContractEntry">继续流程</el-button>
              <el-button type="danger" @click="deleteEntryProcessThink"
                >中止流程</el-button
              >
            </template>
          </div>
        </div>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="企业名称">{{
          companyInfo.companyName || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="载体">{{
          companyInfo.zt || companyInfo.intentionProject || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="客户意向等级">{{
          companyInfo.customerIntentionLevel == 4
            ? "A级 (已缴纳意向金)"
            : companyInfo.customerIntentionLevel == 3
            ? "B级 (1个月内可签约)"
            : companyInfo.customerIntentionLevel == 2
            ? "C级 (3个月内需持续培育)"
            : companyInfo.customerIntentionLevel == 1
            ? "D级 (明确表示无意向)"
            : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="渠道来源">{{
          companyInfo.customerSource || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="客户入驻形态">{{
          companyInfo.checkInType || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="企业所在区域">{{
          companyInfo.enterpriseProvince ||
          companyInfo.enterpriseCity ||
          companyInfo.enterpriseDistrict
            ? [
                companyInfo.enterpriseProvince,
                companyInfo.enterpriseCity,
                companyInfo.enterpriseDistrict,
              ]
                .filter(Boolean)
                .join(" ")
            : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="上年税收(万元)">{{
          companyInfo.annualTax || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="所属行业">{{
          companyInfo.industryCategory || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="招商目的">{{
          companyInfo.investmentPurpose || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="资源能力">{{
          companyInfo.resourceCapability || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="企业资质">{{
          companyInfo.enterpriseQualification || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="企业人数">{{
          companyInfo.employeeCount || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="主营业务">{{
          companyInfo.mainBusiness || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="主要关注点">{{
          companyInfo.focusPoint || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="入驻方式">{{
          companyInfo.entryMode || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="招商员">{{
          companyInfo.merchants || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="注册类型">{{
          companyInfo.companyClass || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="房间号">{{
          companyInfo.roomNum || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="入驻状态">
          <el-tag type="primary">{{
            !companyInfo.status || companyInfo.status == 0
              ? "未开始入驻流程"
              : companyInfo.status == 1
              ? "备案中"
              : companyInfo.status == 2
              ? "合同拟定中"
              : companyInfo.status == 3
              ? "办证中"
              : companyInfo.status == 4 && companyInfo.processId
              ? "入驻中流程"
              : "入驻中"
          }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-tabs v-model="activeTab" type="card" style="margin-top: 20px">
      <el-tab-pane label="合同管理" name="paymentPlan">
        <!-- 欠费回款计划 -->
        <div v-if="arrearsList.length > 0" class="arrears-section">
          <h3 class="section-title">欠费回款计划</h3>
          <el-table
            :data="arrearsList"
            border
            style="width: 100%"
            v-loading="arrearsLoading"
            max-height="300px"
          >
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="cycle" label="缴费周期" width="340" />
            <el-table-column prop="unitPrice" label="单价" />
            <el-table-column prop="monthPrice" label="月度费用" />
            <el-table-column prop="startTime" label="应缴费用时间" width="140" />
            <el-table-column prop="amount" label="应缴费用金额" width="120" />
            <el-table-column prop="paidAmount" label="已付金额" />
            <el-table-column prop="remainingAmount" label="剩余金额" />
            <el-table-column prop="type" label="费用类型" />
            <el-table-column prop="remake" label="备注" width="340" />
          </el-table>
          <pagination
            v-show="arrearsTotal > 0"
            :total="arrearsTotal"
            :page="arrearsQueryParams.pageNum"
            :limit="arrearsQueryParams.pageSize"
            @pagination="handleArrearsPagination"
          />
        </div>
        <!-- 添加标签页用于分类显示回款计划 -->
        <el-tabs
          v-model="activePlanTab"
          @tab-change="handlePlanTabChange"
          class="plan-tabs"
        >
          <el-tab-pane label="合同总表" name="all"></el-tab-pane>
          <el-tab-pane label="进行中合同" name="notEnd"></el-tab-pane>
          <el-tab-pane
            label="待续租实体合同"
            name="nearly"
            v-if="companyInfo.entryMode != '挂靠'"
          ></el-tab-pane>
          <el-tab-pane label="完结合同" name="finished"></el-tab-pane>
          <el-tab-pane label="待退用合同" name="toBeDiscarded"></el-tab-pane>
          <el-tab-pane label="退用合同" name="discarded"></el-tab-pane>
        </el-tabs>

        <div v-if="paymentPlans.length > 0">
          <el-table
            :data="paymentPlans"
            border
            style="width: 100%"
            v-loading="plansLoading"
            row-key="contractNumber"
          >
            <el-table-column type="expand">
              <template #default="props">
                <div class="payment-plan-container">
                  <el-table :data="props.row.paymentPlanList" border style="width: 100%">
                    <el-table-column label="周期" min-width="200" align="left">
                      <template #default="{ row }">
                        {{ row.cycle }}
                      </template>
                    </el-table-column>

                    <el-table-column label="单价" width="120" align="left">
                      <template #default="{ row }"> {{ row.unitPrice }} 元 </template>
                    </el-table-column>
                    <el-table-column label="月价" width="120" align="left">
                      <template #default="{ row }"> {{ row.monthPrice }} 元 </template>
                    </el-table-column>
                    <el-table-column label="开始时间" width="150" align="left">
                      <template #default="{ row }">
                        {{ row.startTime }}
                      </template>
                    </el-table-column>
                    <el-table-column label="金额" width="120" align="left">
                      <template #default="{ row }"> {{ row.amount }} 元 </template>
                    </el-table-column>
                    <el-table-column label="已付金额" width="120" align="left">
                      <template #default="{ row }"> {{ row.paidAmount }} 元 </template>
                    </el-table-column>
                    <el-table-column label="剩余金额" width="120" align="left">
                      <template #default="{ row }">
                        {{ row.remainingAmount }} 元
                      </template>
                    </el-table-column>
                    <el-table-column label="类型" width="120" align="left">
                      <template #default="{ row }">
                        {{ row.type }}
                      </template>
                    </el-table-column>
                    <el-table-column label="备注" min-width="200" align="left">
                      <template #default="{ row }">
                        {{ row.remake }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="合同编号" width="300" align="left">
              <template #default="{ row }">
                {{ row.contractNumber }}
              </template>
            </el-table-column>
            <el-table-column label="合同类型" width="120" align="left">
              <template #default="{ row }"> {{ row.type }}</template>
            </el-table-column>
            <el-table-column label="承租方" width="200" align="left">
              <template #default="{ row }">
                {{ row.lesseeName }}
              </template>
            </el-table-column>
            <el-table-column label="出租方" width="200" align="left">
              <template #default="{ row }">
                {{ row.carrierName }}
              </template>
            </el-table-column>
            <el-table-column label="租赁期限" align="left" width="350">
              <template #default="{ row }">
                {{ row.leaseTerm }}
              </template>
            </el-table-column>
            <el-table-column label="租金单价" width="120" align="left">
              <template #default="{ row }">
                {{ row.unitRentPrice }} 元/平方米/月
              </template>
            </el-table-column>
            <el-table-column label="面积" width="120" align="left">
              <template #default="{ row }"> {{ row.area }} 平方米 </template>
            </el-table-column>
            <el-table-column label="金额" width="120" align="left">
              <template #default="{ row }"> {{ row.amount }} 元 </template>
            </el-table-column>
            <el-table-column label="租赁保证金" width="150" align="left" fixed="right">
              <template #default="{ row }"> {{ row.securityDeposit }} 元 </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="210"
              align="left"
              fixed="right"
              v-if="companyInfo.status >= 4 && !companyInfo.processId"
            >
              <template #default="{ row }">
                <el-button
                  type="primary"
                  @click="handleChangeBtn(row)"
                  v-if="row.type != '虚拟'"
                  >合同变更</el-button
                >
                <el-button
                  type="danger"
                  @click="handleWithdrawalBtn(row)"
                  v-if="row.type != '虚拟'"
                  >退租</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-empty v-else description="暂无回款计划数据" />
      </el-tab-pane>
      <el-tab-pane
        label="回款明细"
        name="paymentLog"
        v-if="companyInfo.entryMode != '挂靠'"
      >
        <div class="record-container">
          <el-table
            :data="paymentLogData"
            border
            style="width: 100%"
            v-loading="logLoading"
          >
            <el-table-column type="index" label="序号" width="100" align="left" />

            <el-table-column prop="planId" label="计划ID" width="180" align="left" />
            <el-table-column prop="historyId" label="流水ID" width="200" align="left" />
            <el-table-column prop="amount" label="缴费金额" width="200" align="left" />
            <el-table-column prop="createTime" label="创建时间" align="left" />
            <el-table-column prop="updateTime" label="修改时间" align="left" />
            <!-- <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="primary" link>查看详情</el-button>
              </template>
            </el-table-column> -->
          </el-table>
          <!-- 回款明细分页组件 -->
          <pagination
            v-show="logTotal > 0"
            :total="logTotal"
            :page="logQueryParams.pageNum"
            :limit="logQueryParams.pageSize"
            @pagination="handleLogPagination"
          />
        </div>
      </el-tab-pane>

      <el-tab-pane
        label="缴费流水"
        name="paymentHistory"
        v-if="companyInfo.entryMode != '挂靠'"
      >
        <div class="record-container">
          <!-- 新增按钮 -->
          <el-button
            v-if="!isReadOnly && companyInfo.status >= 3"
            type="primary"
            @click="handleAddPaymentHistory"
            class="add-payment-btn"
          >
            新增缴费流水
          </el-button>

          <el-form
            v-if="paymentHistoryDialogVisible"
            :model="paymentHistoryForm"
            :rules="paymentHistoryRules"
            ref="paymentHistoryFormRef"
            label-width="100px"
            class="payment-history-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="总金额" prop="amount">
                  <el-input-number
                    v-model="paymentHistoryForm.amount"
                    :min="0"
                    :precision="2"
                    :step="100"
                    controls-position="right"
                    style="width: 100%"
                    placeholder="请输入总金额"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同编号" prop="contractNumber">
                  <el-select
                    v-model="paymentHistoryForm.contractNumber"
                    placeholder="请选择合同编号"
                    style="width: 100%"
                    :loading="contractListLoading"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="contract in contractList"
                      :key="contract.id"
                      :label="contract.contractNumber"
                      :value="contract.contractNumber"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <div class="form-actions">
              <el-button @click="paymentHistoryDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitPaymentHistoryForm">确定</el-button>
            </div>
          </el-form>

          <el-table
            :data="paymentHistoryData"
            border
            class="payment-history-table"
            v-loading="historyLoading"
          >
            <el-table-column type="index" label="序号" width="80" align="left" />
            <el-table-column
              prop="contractNumber"
              label="合同编号"
              width="250"
              align="left"
            />
            <el-table-column prop="amount" label="总金额" width="120" align="left" />
            <el-table-column
              prop="remainingAmount"
              label="剩余金额"
              width="120"
              align="left"
            />
            <el-table-column prop="paidAmount" label="已付金额" align="left" />
            <el-table-column prop="createTime" label="创建时间" align="left" />
            <el-table-column prop="updateTime" label="修改时间" align="left" />
            <el-table-column label="操作" width="150" align="left" fixed="right">
              <template #default="{ row }">
                <!-- <el-button type="primary" link @click="handleEditPaymentHistory(row)">
                  修改
                </el-button> -->
                <el-button type="danger" link @click="handleDeletePaymentHistory(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 缴费流水分页组件 -->
          <pagination
            v-show="historyTotal > 0"
            :total="historyTotal"
            :page="historyQueryParams.pageNum"
            :limit="historyQueryParams.pageSize"
            @pagination="handleHistoryPagination"
            class="pagination-container"
          />
        </div>
      </el-tab-pane>

      <el-tab-pane label="入驻流程文件" name="processFiles">
        <el-card class="file-list-card">
          <div v-if="companyInfo.entryMode === '挂靠'">
            <el-tabs v-model="activeTab_file" class="record-tabs">
              <el-tab-pane label="备案" name="1" v-if="companyInfo.status >= 1">
                <div>
                  <h3>备案环节文件</h3>
                  <div class="file-section">
                    <div class="file-group">
                      <div class="file-label">备案表</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.record"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group" v-if="companyInfo.companyClass !== '迁址'">
                      <div class="file-label">信息注册表</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.info"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">法人签字笔迹</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.sign"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">自然人身份证</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.id"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">非自然人营业执照</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.license"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="合同" name="2" v-if="companyInfo.status >= 2">
                <div>
                  <h3>合同环节文件</h3>
                  <div class="file-section">
                    <div class="file-group">
                      <div class="file-label">虚拟合同归档文件</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.virtualArchive"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="发票/物业/办证" name="3" v-if="companyInfo.status >= 3">
                <div v-if="companyInfo.status >= 3">
                  <h3>办证环节文件</h3>
                  <div class="file-section">
                    <div class="file-group">
                      <div class="file-label">法人签字笔迹</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.sign"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">自然人身份证</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.id"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">非自然人营业执照</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.license"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">营业执照</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.licensePdf"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div></el-tab-pane
              >
              <!-- <el-tab-pane label="入驻告知" name="4" v-if="companyInfo.status >= 4"></el-tab-pane> -->
            </el-tabs>
          </div>

          <div v-else>
            <el-tabs v-model="activeTab_file" class="record-tabs">
              <el-tab-pane label="备案" name="1" v-if="companyInfo.status >= 1">
                <div>
                  <h3>备案环节文件</h3>
                  <div class="file-section">
                    <div class="file-group">
                      <div class="file-label">备案表</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.record"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group" v-if="companyInfo.companyClass !== '迁址'">
                      <div class="file-label">信息注册表</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.info"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">法人签字笔迹</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.sign"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">自然人身份证</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.id"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">非自然人营业执照</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.license"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="合同" name="2" v-if="companyInfo.status >= 2">
                <div v-if="companyInfo.status >= 2">
                  <h3>合同环节文件</h3>
                  <div class="file-section">
                    <div class="file-group">
                      <div class="file-label">实体合同归档文件</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.contractArchive"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">虚拟合同归档文件</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.virtualArchive"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="办证" name="3" v-if="companyInfo.status >= 3">
                <div v-if="companyInfo.status >= 3">
                  <h3>办证环节文件</h3>
                  <div class="file-section">
                    <div class="file-group">
                      <div class="file-label">入驻前图片</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.beforeDecoration"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">入驻后图片</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.afterDecoration"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">物业交接单</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.propertyHandover"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">平面图(PDF)</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.planPdf"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">平面图(ZIP)</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.planZip"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">水表</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.waterMeter"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">电表</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.electricMeter"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="file-group">
                      <div class="file-label">营业执照</div>
                      <div class="file-list">
                        <el-tag
                          v-for="file in fileList.licensePdf"
                          :key="file.id"
                          type="success"
                          @click="previewFile(file)"
                          class="file-tag"
                        >
                          {{ file.fileName }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <!-- <el-tab-pane label="入驻告知" name="4" v-if="companyInfo.status >= 4"></el-tab-pane> -->
            </el-tabs>
          </div>

          <el-empty
            v-if="Object.keys(fileList).length === 0"
            description="暂无文件数据"
          />
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="合同变更日志" name="cancellationLog">
        <div class="record-container">
          <el-tabs v-model="activeTabLog" @tab-change="handleTabChange">
            <!-- 合同退租日志tab -->
            <el-tab-pane label="合同退租日志" name="cancellation">
              <el-card class="list-card" style="margin-top: 18px">
                <el-table :data="cancellationLogData" style="width: 100%" border>
                  <el-table-column
                    prop="id"
                    label="Id"
                    width="80"
                    sortable
                    align="left"
                  />
                  <el-table-column
                    prop="createTime"
                    label="变更时间"
                    width="180"
                    sortable
                    align="left"
                  />
                  <el-table-column
                    prop="contractNumber"
                    label="合同编号"
                    width="320"
                    align="left"
                  />
                  <el-table-column
                    prop="cancellationBy"
                    label="操作人员"
                    width="120"
                    align="left"
                  />
                  <el-table-column
                    prop="cancellationer"
                    label="退租方"
                    width="120"
                    align="left"
                  />
                  <el-table-column
                    prop="cancellationReason"
                    label="退租原因"
                    width="200"
                    align="left"
                  />
                  <el-table-column
                    prop="operator"
                    label="经办人"
                    width="120"
                    align="left"
                  />
                  <el-table-column prop="cancellationRemake" label="备注" align="left" />
                </el-table>
                <pagination
                  v-show="cancellationTotal > 0"
                  :total="cancellationTotal"
                  v-model:page="cancellationQueryParams.pageNum"
                  v-model:limit="cancellationQueryParams.pageSize"
                  @pagination="handleCancellationPagination"
                />
              </el-card>
            </el-tab-pane>

            <!-- 合同变更日志tab -->
            <el-tab-pane label="合同变更日志" name="changeLog">
              <el-card class="list-card" style="margin-top: 18px">
                <el-table
                  v-loading="changeLogLoading"
                  :data="changeLogList"
                  style="width: 100%"
                  border
                >
                  <el-table-column label="序号" width="80" type="index" align="left" />
                  <el-table-column
                    prop="companyName"
                    label="企业名称"
                    width="260"
                    sortable
                    align="left"
                  />
                  <el-table-column
                    prop="contractNumber"
                    label="合同编号"
                    width="320"
                    align="left"
                  />
                  <el-table-column prop="type" label="变更类型" width="100" align="left">
                    <template #default="scope">
                      <el-tag v-if="scope.row.type === 2">扩租</el-tag>
                      <el-tag v-else-if="scope.row.type === 3" type="warning"
                        >缩租</el-tag
                      >
                      <el-tag v-else-if="scope.row.type === 4" type="success"
                        >续租</el-tag
                      >
                      <span v-else>{{ scope.row.type }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="isRehandleCertificate"
                    label="重新办证"
                    width="100"
                    align="left"
                  >
                    <template #default="scope">
                      <el-tag v-if="scope.row.isRehandleCertificate === 1" type="success"
                        >是</el-tag
                      >
                      <el-tag v-else type="info">否</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="isAbandonOriginalContract"
                    label="退用原合同"
                    width="120"
                    align="left"
                  >
                    <template #default="scope">
                      <el-tag
                        v-if="scope.row.isAbandonOriginalContract === 1"
                        type="success"
                        >是</el-tag
                      >
                      <el-tag v-else type="info">否</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="operator"
                    label="经办人"
                    width="120"
                    align="left"
                  />
                  <el-table-column
                    prop="remake"
                    label="备注"
                    fixed="right"
                    align="left"
                  />
                </el-table>
                <pagination
                  v-show="changeLogTotal > 0"
                  :total="changeLogTotal"
                  v-model:page="changeLogQueryParams.pageNum"
                  v-model:limit="changeLogQueryParams.pageSize"
                  @pagination="getChangeLogList"
                />
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 文件预览弹窗 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="'文件预览: ' + previewFileName"
      width="70vw"
      top="5vh"
      class="file-preview-dialog"
    >
      <template v-if="previewFileType === 'image'">
        <div class="image-preview-container">
          <img :src="previewFileUrl" alt="图片预览" class="preview-image" />
        </div>
      </template>
      <template v-else-if="previewFileType === 'pdf'">
        <div class="pdf-preview-container">
          <iframe :src="previewFileUrl" class="preview-iframe" title="PDF预览" />
        </div>
      </template>
      <template
        v-else-if="
          previewFileType === 'word' ||
          previewFileType === 'excel' ||
          previewFileType === 'ppt'
        "
      >
        <div class="office-preview-container">
          <iframe
            :src="`https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(
              previewFileUrl
            )}`"
            class="preview-iframe"
            title="Office文档预览"
          />
          <div class="preview-tip">如果文档未能正常显示，请点击下方按钮下载后查看</div>
        </div>
      </template>
      <template v-else-if="previewFileType === 'txt'">
        <div class="txt-preview-container">
          <iframe :src="previewFileUrl" class="preview-iframe" title="文本文件预览" />
        </div>
      </template>
      <template v-else-if="previewFileType === 'archive'">
        <el-alert
          type="info"
          :closable="false"
          title="压缩文件无法在线预览，请下载后本地解压查看。"
          class="preview-alert"
        />
      </template>
      <template v-else>
        <el-alert
          type="warning"
          :closable="false"
          title="暂不支持此类型文件在线预览，可下载后本地打开。"
          class="preview-alert"
        />
      </template>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDownloadFile">下载文件</el-button>
        </div>
      </template>
    </el-dialog>
    <payment-modal
      v-model="showPaymentModal"
      :company-id="companyId"
      :plan-id="planId"
      @success="handlePaymentSuccess"
      @close="handlePaymentClose"
    />

    <!-- 编辑企业信息弹窗 -->
    <el-dialog
      v-model="editCompanyInfoDialogVisible"
      title="编辑企业信息"
      width="600px"
      :before-close="handleEditCompanyInfoClose"
    >
      <el-form
        ref="editCompanyInfoFormRef"
        :model="editCompanyInfoForm"
        :rules="editCompanyInfoRules"
        label-width="120px"
        class="info-form"
      >
        <el-form-item label="企业名称" prop="companyName">
          <el-input
            v-model="editCompanyInfoForm.companyName"
            placeholder="请输入企业名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="载体" prop="intentionProject">
          <el-select
            v-model="editCompanyInfoForm.intentionProject"
            placeholder="请选择载体"
            clearable
            @focus="handleSelectFocus('intentionProject')"
            filterable
            :loading="dropdownLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in dropdownData.intentionProject"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="客户意向等级" prop="customerIntentionLevel">
          <el-select
            v-model="editCompanyInfoForm.customerIntentionLevel"
            placeholder="请选择客户意向等级"
            style="width: 100%"
            clearable
          >
            <el-option label="A级 (已缴纳意向金)" value="A级 (已缴纳意向金)" />
            <el-option label="B级 (1个月内可签约)" value="B级 (1个月内可签约)" />
            <el-option label="C级 (3个月内需持续培育)" value="C级 (3个月内需持续培育)" />
            <el-option label="D级 (明确表示无意向)" value="D级 (明确表示无意向)" />
          </el-select>
        </el-form-item>

        <el-form-item label="渠道来源" prop="customerSource">
          <el-select
            v-model="editCompanyInfoForm.customerSource"
            placeholder="请选择拓客渠道来源"
            style="width: 100%"
            clearable
          >
            <el-option
              label="自主招商(陌拜call客、电话销售)"
              value="自主招商(陌拜call客、电话销售)"
            />
            <el-option label="中介" value="中介" />
            <el-option label="新媒体/网络平台" value="新媒体/网络平台" />
            <el-option label="以商引商" value="以商引商" />
            <el-option label="陌拜电Call" value="陌拜电Call" />
            <el-option label="展会论坛" value="展会论坛" />
            <el-option label="人才渠道" value="人才渠道" />
            <el-option label="政府推荐" value="政府推荐" />
            <el-option label="公司资源" value="公司资源" />
            <el-option label="商会/协会资源" value="商会/协会资源" />
            <el-option label="同行载体推荐" value="同行载体推荐" />
            <el-option label="园内企业扩租" value="园内企业扩租" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="客户入驻形态" prop="checkInType">
          <el-select
            v-model="editCompanyInfoForm.checkInType"
            placeholder="请选择客户入驻形态"
            style="width: 100%"
            clearable
          >
            <el-option label="实体-新注册" value="实体-新注册" />
            <el-option label="未定" value="未定" />
            <el-option label="实体-迁址" value="实体-迁址" />
            <el-option label="挂靠-新注册" value="挂靠-新注册" />
            <el-option label="挂靠-迁址" value="挂靠-迁址" />
          </el-select>
        </el-form-item>

        <el-form-item label="企业所在地区" prop="enterpriseAddress">
          <el-cascader
            v-model="editCompanyInfoForm.enterpriseAddress"
            :options="processedRegionData"
            clearable
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择企业所在地区"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="上年税收(万元)" prop="annualTax">
          <el-input
            v-model="editCompanyInfoForm.annualTax"
            placeholder="请输入上年税收"
            clearable
          />
        </el-form-item>

        <el-form-item label="所属行业" prop="industry">
          <el-select
            v-model="editCompanyInfoForm.industry"
            placeholder="请选择所属行业"
            style="width: 100%"
            clearable
          >
            <el-option label="医疗行业机构" value="医疗行业机构" />
            <el-option
              label="药品药物研发、生产及销售"
              value="药品药物研发、生产及销售"
            />
            <el-option
              label="医疗器械研发、生产及销售"
              value="医疗器械研发、生产及销售"
            />
            <el-option
              label="医疗器械销售(注册人制公司)"
              value="医疗器械销售(注册人制公司)"
            />
            <el-option
              label="医疗端即质行业机构-医生集团运营"
              value="医疗端即质行业机构-医生集团运营"
            />
            <el-option
              label="智慧养老(适老化改造/智能家居)"
              value="智慧养老(适老化改造/智能家居)"
            />
            <el-option label="健康产品电商与直播运营" value="健康产品电商与直播运营" />
            <el-option
              label="环境治理（技术解决方案及施工运维）"
              value="环境治理（技术解决方案及施工运维）"
            />
            <el-option label="环境检测" value="环境检测" />
            <el-option
              label="环境咨询（环境影响评估、场地环境调查）"
              value="环境咨询（环境影响评估、场地环境调查）"
            />
            <el-option label="低空经济" value="低空经济" />
            <el-option label="新能源" value="新能源" />
            <el-option label="新一代信息技术" value="新一代信息技术" />
            <el-option label="现代服务业与金融" value="现代服务业与金融" />
            <el-option label="房地产与建筑工程" value="房地产与建筑工程" />
            <el-option label="交通运输" value="交通运输" />
            <el-option label="商业销售" value="商业销售" />
            <el-option label="工业销售" value="工业销售" />
            <el-option label="新材料" value="新材料" />
            <el-option label="文化创意" value="文化创意" />
            <el-option label="现代农业科技" value="现代农业科技" />
          </el-select>
        </el-form-item>

        <el-form-item label="招商目的" prop="investmentPurpose">
          <el-select
            v-model="editCompanyInfoForm.investmentPurpose"
            placeholder="请选择招商目的"
            style="width: 100%"
            clearable
          >
            <el-option label="人才申报" value="人才申报" />
            <el-option label="载体去化" value="载体去化" />
            <el-option label="税收" value="税收" />
            <el-option label="渠道" value="渠道" />
            <el-option label="产业资源" value="产业资源" />
            <el-option label="政府资源" value="政府资源" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="资源能力" prop="resourceCapability">
          <el-select
            v-model="editCompanyInfoForm.resourceCapability"
            placeholder="请选择客户资源能力"
            style="width: 100%"
            clearable
          >
            <el-option label="无" value="无" />
            <el-option label="企业出海" value="企业出海" />
            <el-option label="资源引荐" value="资源引荐" />
            <el-option label="客户推介" value="客户推介" />
            <el-option label="政策支持指导" value="政策支持指导" />
            <el-option label="应用场景提供" value="应用场景提供" />
            <el-option label="产业规划" value="产业规划" />
            <el-option label="校友资源" value="校友资源" />
            <el-option label="同乡资源" value="同乡资源" />
            <el-option label="产业导师" value="产业导师" />
            <el-option label="上下游链接" value="上下游链接" />
            <el-option label="产学研合作" value="产学研合作" />
            <el-option label="校地企合作" value="校地企合作" />
            <el-option label="企业申报服务" value="企业申报服务" />
            <el-option label="法律服务" value="法律服务" />
            <el-option label="投融资服务" value="投融资服务" />
            <el-option label="健康服务" value="健康服务" />
          </el-select>
        </el-form-item>

        <el-form-item label="企业资质" prop="enterpriseQualification">
          <el-select
            v-model="editCompanyInfoForm.enterpriseQualification"
            placeholder="请选择企业资质"
            style="width: 100%"
            clearable
          >
            <el-option label="高新技术企业" value="高新技术企业" />
            <el-option label='专精特新 "小巨人"' value='专精特新 "小巨人"' />
            <el-option label="创新型中小企业" value="创新型中小企业" />
            <el-option label="科技型中小企业" value="科技型中小企业" />
            <el-option label="中小微企业" value="中小微企业" />
            <el-option label="独角兽" value="独角兽" />
            <el-option label="瞪羚企业" value="瞪羚企业" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="企业人数" prop="employeeCount">
          <el-select
            v-model="editCompanyInfoForm.employeeCount"
            placeholder="请选择企业人数"
            style="width: 100%"
            clearable
          >
            <el-option label="< 10" value="< 10" />
            <el-option label="10-50" value="10-50" />
            <el-option label="50-200" value="50-200" />
            <el-option label="> 200" value="> 200" />
          </el-select>
        </el-form-item>

        <el-form-item label="主营业务" prop="mainBusiness">
          <el-input
            v-model="editCompanyInfoForm.mainBusiness"
            placeholder="请输入主营业务"
            type="textarea"
            :rows="4"
          />
        </el-form-item>

        <el-form-item label="主要关注点" prop="focusPoint">
          <el-input
            v-model="editCompanyInfoForm.focusPoint"
            placeholder="请输入主要关注点"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditCompanyInfoClose">取消</el-button>
          <el-button type="primary" @click="submitEditCompanyInfoForm">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="contractDialogVisible"
      title="合同操作"
      width="500px"
      class="contract-dialog"
    >
      <el-form
        :model="contractForm"
        :rules="contractFormRules"
        ref="contractFormRef"
        label-width="120px"
        class="contract-form"
      >
        <el-form-item label="是否退用原合同">
          <el-switch
            v-model="contractForm.isAbandonOriginalContract"
            active-text="是"
            inactive-text="否"
          />
          <!-- @change="handleAbandonContractChange" -->
        </el-form-item>

        <el-form-item label="是否重新办证">
          <el-switch
            v-model="contractForm.isRehandleCertificate"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="合同变更" prop="selectedContract">
          <el-select
            v-model="contractForm.selectedContract"
            placeholder="请选择需要变更的合同"
            style="width: 100%"
            :loading="contractListLoading"
            clearable
          >
            <el-option
              v-for="contract in contractList"
              :key="contract.id"
              :label="contract.contractNumber"
              :value="contract.contractNumber"
            />
          </el-select>
          <div class="form-item-tip">请选择需要变更的合同</div>
        </el-form-item>
        <el-form-item label="合同变更类型" prop="contractChangeType">
          <el-select
            v-model="contractForm.actionType"
            placeholder="请选择合同变更类型"
            style="width: 100%"
            clearable
          >
            <el-option label="合同变更" value="合同变更" />
            <!-- <el-option label="扩租" value="expansion" />
            <el-option label="缩租" value="reduction" />
            <el-option label="续租" value="renewal" /> -->
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="contractDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleContractSubmit"
            >确定发起合同变更</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 企业退租 -->
    <el-dialog
      v-model="withdrawalDialogVisibleCompany"
      title="企业退租确认"
      width="80%"
      class="withdrawal-dialog"
    >
      <div>
        <h3 class="section-title">待续租实体合同列表及回款计划</h3>
        <div v-if="nearlyPaymentPlans.length > 0">
          <el-table
            :data="nearlyPaymentPlans"
            border
            style="width: 100%"
            v-loading="plansLoading"
            row-key="contractNumber"
          >
            <!-- 单选列：使用自定义列渲染 radio，确保只能选择一条 -->

            <el-table-column type="expand">
              <template #default="props">
                <div class="payment-plan-container">
                  <el-table :data="props.row.paymentPlanList" border style="width: 100%">
                    <el-table-column label="周期" min-width="320" align="left">
                      <template #default="{ row }">
                        {{ row.cycle }}
                      </template>
                    </el-table-column>

                    <el-table-column label="单价" width="120" align="left">
                      <template #default="{ row }"> {{ row.unitPrice }} 元 </template>
                    </el-table-column>
                    <el-table-column label="月价" width="120" align="left">
                      <template #default="{ row }"> {{ row.monthPrice }} 元 </template>
                    </el-table-column>
                    <el-table-column label="开始时间" width="150" align="left">
                      <template #default="{ row }">
                        {{ row.startTime }}
                      </template>
                    </el-table-column>
                    <el-table-column label="金额" width="120" align="left">
                      <template #default="{ row }"> {{ row.amount }} 元 </template>
                    </el-table-column>
                    <el-table-column label="已付金额" width="120" align="left">
                      <template #default="{ row }"> {{ row.paidAmount }} 元 </template>
                    </el-table-column>
                    <el-table-column label="剩余金额" width="120" align="left">
                      <template #default="{ row }">
                        {{ row.remainingAmount }} 元
                      </template>
                    </el-table-column>
                    <el-table-column label="类型" width="120" align="left">
                      <template #default="{ row }">
                        {{ row.type }}
                      </template>
                    </el-table-column>
                    <el-table-column label="备注" min-width="200" align="left">
                      <template #default="{ row }">
                        {{ row.remake }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="合同编号" width="320" align="left" fixed="left">
              <template #default="{ row }">
                {{ row.contractNumber }}
              </template>
            </el-table-column>
            <el-table-column label="合同类型" width="120" align="left">
              <template #default="{ row }"> {{ row.type }}</template>
            </el-table-column>
            <el-table-column label="承租方" width="180" align="left">
              <template #default="{ row }">
                {{ row.lesseeName }}
              </template>
            </el-table-column>
            <el-table-column label="出租方" width="180" align="left">
              <template #default="{ row }">
                {{ row.carrierName }}
              </template>
            </el-table-column>
            <el-table-column label="租赁期限" width="300" align="left">
              <template #default="{ row }">
                {{ row.leaseTerm }}
              </template>
            </el-table-column>
            <el-table-column label="租金单价" width="120" align="left">
              <template #default="{ row }">
                {{ row.unitRentPrice }} 元/平方米/月
              </template>
            </el-table-column>
            <el-table-column label="面积" width="120" align="left">
              <template #default="{ row }"> {{ row.area }} 平方米 </template>
            </el-table-column>
            <el-table-column label="金额" width="120" align="left">
              <template #default="{ row }"> {{ row.amount }} 元 </template>
            </el-table-column>
            <el-table-column label="租赁保证金" width="150" align="left" fixed="right">
              <template #default="{ row }"> {{ row.securityDeposit }} 元 </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="selectedContract">
          <h3 class="section-title" style="margin-top: 20px">合同回款计划</h3>
          <el-table
            :data="selectedContractPlans"
            border
            style="width: 100%"
            v-loading="plansLoading"
          >
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="cycle" label="缴费周期" />
            <el-table-column prop="unitPrice" label="单价" />
            <el-table-column prop="monthPrice" label="月度费用" />
            <el-table-column prop="startTime" label="应缴费用时间" />
            <el-table-column prop="amount" label="应缴费用金额" />
            <el-table-column prop="paidAmount" label="已付金额" />
            <el-table-column prop="remainingAmount" label="剩余金额" />
            <el-table-column prop="type" label="费用类型" />
            <el-table-column prop="remake" label="备注" />
          </el-table>
        </div>

        <h3 class="section-title" style="margin-top: 20px" v-if="!selectedContract">
          欠费回款计划
        </h3>
        <el-table
          v-if="!selectedContract"
          :data="arrearsList"
          border
          style="width: 100%"
          v-loading="arrearsLoading"
          max-height="400px"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="cycle" label="缴费周期" />
          <el-table-column prop="unitPrice" label="单价" />
          <el-table-column prop="monthPrice" label="月度费用" />
          <el-table-column prop="startTime" label="应缴费用时间" />
          <el-table-column prop="amount" label="应缴费用金额" />
          <el-table-column prop="paidAmount" label="已付金额" />
          <el-table-column prop="remainingAmount" label="剩余金额" />
          <el-table-column prop="type" label="费用类型" />
          <el-table-column prop="remake" label="备注" />
        </el-table>
        <pagination
          v-show="arrearsTotal > 0"
          :total="arrearsTotal"
          :page="arrearsQueryParams.pageNum"
          :limit="arrearsQueryParams.pageSize"
          @pagination="handleArrearsPagination"
        />

        <!-- 退租表单 -->
        <el-form
          :model="withdrawalForm"
          :rules="withdrawalFormRules"
          ref="withdrawalFormRef"
          label-width="120px"
          style="margin-top: 20px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="退租方" prop="cancellationer">
                <el-select
                  v-model="withdrawalForm.cancellationer"
                  placeholder="请选择退租方"
                  style="width: 100%"
                >
                  <el-option label="我司退租" value="我司退租" />
                  <el-option label="租户退租" value="租户退租" />
                  <el-option label="三方原因" value="三方原因" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="退租原因" prop="cancellationReason">
                <el-input
                  v-model="withdrawalForm.cancellationReason"
                  placeholder="请输入退租原因"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注说明" prop="cancellationRemake">
            <el-input
              v-model="withdrawalForm.cancellationRemake"
              type="textarea"
              placeholder="请输入备注说明"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="withdrawalDialogVisibleCompany = false">取消</el-button>
          <el-button
            :disabled="!selectedContract"
            type="warning"
            @click="handleDefaultDeposit"
          >
            押金转违约金
          </el-button>
          <el-button
            :disabled="!selectedContract"
            type="primary"
            @click="handleDepositRefund"
          >
            押金退费
          </el-button>
          <el-button
            :disabled="!selectedContract"
            type="success"
            @click="handleDepositToRent"
          >
            押金转租期
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 合同退租确认弹窗 -->
    <el-dialog
      v-model="withdrawalDialogVisible"
      title="合同退租确认"
      width="80%"
      class="withdrawal-dialog"
    >
      <div>
        <h3 class="section-title">待续租实体合同列表及回款计划</h3>
        <div v-if="nearlyPaymentPlans.length > 0">
          <el-table
            :data="nearlyPaymentPlans"
            border
            style="width: 100%"
            v-loading="plansLoading"
            row-key="contractNumber"
          >
            <!-- 单选列：使用自定义列渲染 radio，确保只能选择一条 -->
            <el-table-column label="选择" width="80" fixed="left">
              <template #default="{ row }">
                <el-radio
                  :model-value="selectedContract && selectedContract.contractNumber"
                  :label="row.contractNumber"
                  @change="() => handleContractSelectionChange(row)"
                />
              </template>
            </el-table-column>
            <el-table-column type="expand">
              <template #default="props">
                <div class="payment-plan-container">
                  <el-table :data="props.row.paymentPlanList" border style="width: 100%">
                    <el-table-column label="周期" min-width="320" align="left">
                      <template #default="{ row }">
                        {{ row.cycle }}
                      </template>
                    </el-table-column>

                    <el-table-column label="单价" width="120" align="left">
                      <template #default="{ row }"> {{ row.unitPrice }} 元 </template>
                    </el-table-column>
                    <el-table-column label="月价" width="120" align="left">
                      <template #default="{ row }"> {{ row.monthPrice }} 元 </template>
                    </el-table-column>
                    <el-table-column label="开始时间" width="150" align="left">
                      <template #default="{ row }">
                        {{ row.startTime }}
                      </template>
                    </el-table-column>
                    <el-table-column label="金额" width="120" align="left">
                      <template #default="{ row }"> {{ row.amount }} 元 </template>
                    </el-table-column>
                    <el-table-column label="已付金额" width="120" align="left">
                      <template #default="{ row }"> {{ row.paidAmount }} 元 </template>
                    </el-table-column>
                    <el-table-column label="剩余金额" width="120" align="left">
                      <template #default="{ row }">
                        {{ row.remainingAmount }} 元
                      </template>
                    </el-table-column>
                    <el-table-column label="类型" width="120" align="left">
                      <template #default="{ row }">
                        {{ row.type }}
                      </template>
                    </el-table-column>
                    <el-table-column label="备注" min-width="200" align="left">
                      <template #default="{ row }">
                        {{ row.remake }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="合同编号" width="320" align="left" fixed="left">
              <template #default="{ row }">
                {{ row.contractNumber }}
              </template>
            </el-table-column>
            <el-table-column label="合同类型" width="120" align="left">
              <template #default="{ row }"> {{ row.type }}</template>
            </el-table-column>
            <el-table-column label="承租方" width="180" align="left">
              <template #default="{ row }">
                {{ row.lesseeName }}
              </template>
            </el-table-column>
            <el-table-column label="出租方" width="180" align="left">
              <template #default="{ row }">
                {{ row.carrierName }}
              </template>
            </el-table-column>
            <el-table-column label="租赁期限" width="300" align="left">
              <template #default="{ row }">
                {{ row.leaseTerm }}
              </template>
            </el-table-column>
            <el-table-column label="租金单价" width="120" align="left">
              <template #default="{ row }">
                {{ row.unitRentPrice }} 元/平方米/月
              </template>
            </el-table-column>
            <el-table-column label="面积" width="120" align="left">
              <template #default="{ row }"> {{ row.area }} 平方米 </template>
            </el-table-column>
            <el-table-column label="金额" width="120" align="left">
              <template #default="{ row }"> {{ row.amount }} 元 </template>
            </el-table-column>
            <el-table-column label="租赁保证金" width="150" align="left" fixed="right">
              <template #default="{ row }"> {{ row.securityDeposit }} 元 </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="selectedContract">
          <h3 class="section-title" style="margin-top: 20px">合同回款计划</h3>
          <el-table
            :data="selectedContractPlans"
            border
            style="width: 100%"
            v-loading="plansLoading"
          >
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="cycle" label="缴费周期" />
            <el-table-column prop="unitPrice" label="单价" />
            <el-table-column prop="monthPrice" label="月度费用" />
            <el-table-column prop="startTime" label="应缴费用时间" />
            <el-table-column prop="amount" label="应缴费用金额" />
            <el-table-column prop="paidAmount" label="已付金额" />
            <el-table-column prop="remainingAmount" label="剩余金额" />
            <el-table-column prop="type" label="费用类型" />
            <el-table-column prop="remake" label="备注" />
          </el-table>
        </div>

        <h3 class="section-title" style="margin-top: 20px" v-if="!selectedContract">
          欠费回款计划
        </h3>
        <el-table
          v-if="!selectedContract"
          :data="arrearsList"
          border
          style="width: 100%"
          v-loading="arrearsLoading"
          max-height="400px"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="cycle" label="缴费周期" />
          <el-table-column prop="unitPrice" label="单价" />
          <el-table-column prop="monthPrice" label="月度费用" />
          <el-table-column prop="startTime" label="应缴费用时间" />
          <el-table-column prop="amount" label="应缴费用金额" />
          <el-table-column prop="paidAmount" label="已付金额" />
          <el-table-column prop="remainingAmount" label="剩余金额" />
          <el-table-column prop="type" label="费用类型" />
          <el-table-column prop="remake" label="备注" />
        </el-table>
        <pagination
          v-show="arrearsTotal > 0"
          :total="arrearsTotal"
          :page="arrearsQueryParams.pageNum"
          :limit="arrearsQueryParams.pageSize"
          @pagination="handleArrearsPagination"
        />

        <!-- 退租表单 -->
        <el-form
          :model="withdrawalForm"
          :rules="withdrawalFormRules"
          ref="withdrawalFormRef"
          label-width="120px"
          style="margin-top: 20px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="退租方" prop="cancellationer">
                <el-select
                  v-model="withdrawalForm.cancellationer"
                  placeholder="请选择退租方"
                  style="width: 100%"
                >
                  <el-option label="我司退租" value="我司退租" />
                  <el-option label="租户退租" value="租户退租" />
                  <el-option label="三方原因" value="三方原因" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="退租原因" prop="cancellationReason">
                <el-input
                  v-model="withdrawalForm.cancellationReason"
                  placeholder="请输入退租原因"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注说明" prop="cancellationRemake">
            <el-input
              v-model="withdrawalForm.cancellationRemake"
              type="textarea"
              placeholder="请输入备注说明"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="withdrawalDialogVisible = false">取消</el-button>
          <el-button
            :disabled="!selectedContract"
            type="warning"
            @click="handleDefaultDeposit"
          >
            押金转违约金
          </el-button>
          <el-button
            :disabled="!selectedContract"
            type="primary"
            @click="handleDepositRefund"
          >
            押金退费
          </el-button>
          <el-button
            :disabled="!selectedContract"
            type="success"
            @click="handleDepositToRent"
          >
            押金转租期
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, watch, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getCompanyInfo,
  getPaymentPlanList,
  getFileByCompanyIdAndTag,
  getCompanyInfoByContractNumber,
  getPaymentHistoryList,
  updatePaymentHistory,
  insertPaymentHistory,
  payment_logList,
  insertEntryProcess,
  DraftContract,
  DraftContractList,
  insertCertification, //办证
  selectById, //当前入驻流程
  getArrearsList, //欠费回款计划列表
  transferDepositToRent, // 押金转租期
  unbindRoom, // 释放房源
  depositRefund, //退租金
  cancellation_infoList, //退租日志
  defaultDeposit,
  getChangeLog, //变更日志
  deleteEntryProcess, // 入驻中流程中止
  deletePaymentHistory, // 删除缴费流水
} from "@/api/company/info";
import { updateCustomerInfo } from "@/api/AttractInvestment/customer/index.js";
import { getBaseCodeInfoList } from "@/api/AttractInvestment/baseCode/index.js";
import { regionData } from "element-china-area-data";
import PaymentModal from "@/views/PaymentModal.vue";
import { selectCompanyTotalByCustomerId } from "@/api/companyTotal/companyTotal.js";
const { proxy } = getCurrentInstance();

// 路由相关
const route = useRoute();
const router = useRouter();
// 只读模式（权限控制）：当通过列表查看档案并带入 readOnly 参数时，隐藏页面所有操作按钮
const isReadOnly = computed(() => {
  const v = route.query.readOnly;
  return v === "1" || v === "true" || v === 1 || v === true;
});

// 处理地区数据：将江苏省放在最前面，并确保包含台湾
const processedRegionData = (() => {
  if (!regionData || !Array.isArray(regionData)) {
    return regionData;
  }

  // 深拷贝数据
  const data = JSON.parse(JSON.stringify(regionData));

  // 查找江苏省和台湾省的索引
  let jiangsuIndex = -1;
  let taiwanIndex = -1;
  let hasTaiwan = false;

  data.forEach((item, index) => {
    // 查找江苏省（可能是"江苏省"或"江苏"）
    if (item.label === "江苏省" || item.label === "江苏") {
      jiangsuIndex = index;
    }
    // 查找台湾省（通过标签或编码710000）
    if (
      item.value === "710000" ||
      item.label === "台湾省" ||
      item.label === "台湾" ||
      item.label === "台湾地区" ||
      item.label.includes("台湾")
    ) {
      taiwanIndex = index;
      hasTaiwan = true;
    }
  });

  // 如果找到江苏省，将其移到最前面
  if (jiangsuIndex > 0) {
    const jiangsuItem = data.splice(jiangsuIndex, 1)[0];
    data.unshift(jiangsuItem);
  }

  // 如果没找到台湾省，添加台湾省数据
  if (!hasTaiwan) {
    // 添加台湾省数据（使用常见的台湾省编码 710000）
    data.push({
      value: "710000",
      label: "台湾省",
      children: [
        {
          value: "710100",
          label: "台北市",
          children: [],
        },
        {
          value: "710200",
          label: "新北市",
          children: [],
        },
        {
          value: "710300",
          label: "桃园市",
          children: [],
        },
        {
          value: "710400",
          label: "台中市",
          children: [],
        },
        {
          value: "710500",
          label: "台南市",
          children: [],
        },
        {
          value: "710600",
          label: "高雄市",
          children: [],
        },
      ],
    });
  }

  return data;
})();

// 根据编码查找对应的中文名称
const findRegionName = (code) => {
  if (!code || !processedRegionData || !Array.isArray(processedRegionData)) {
    return null;
  }

  // 遍历 processedRegionData 找到对应的名称
  const findName = (data, code) => {
    if (!Array.isArray(data)) return null;

    for (const item of data) {
      if (item.value === code) {
        return item.label;
      }
      if (item.children) {
        const result = findName(item.children, code);
        if (result) {
          return result;
        }
      }
    }
    return null;
  };

  return findName(processedRegionData, code);
};

// 下拉框数据
const dropdownLoading = ref(false);
const dropdownData = reactive({
  intentionProject: [], //意向项目 (bigCategory=27)
});

// 下拉框配置映射
const dropdownConfig = {
  intentionProject: 27,
};

// 通用获取下拉框数据方法
const getDropdownData = async (bigCategory, dataKey) => {
  try {
    dropdownLoading.value = true;
    const res = await getBaseCodeInfoList({ bigCategory });

    if (res.code === 200 && Array.isArray(res.rows) && res.rows.length > 0) {
      // 使用 content 字段作为 label 和 value
      dropdownData[dataKey] = res.rows.map((item) => ({
        label: item.content,
        value: item.content,
      }));
    } else {
      dropdownData[dataKey] = [];
      console.warn(`获取${dataKey}数据为空`);
    }
  } catch (error) {
    console.error(`获取${dataKey}数据失败:`, error);
    ElMessage.error(`获取${dataKey}数据失败`);
  } finally {
    dropdownLoading.value = false;
  }
};

// 点击下拉框时加载数据的方法
const handleSelectFocus = (dataKey) => {
  const bigCategory = dropdownConfig[dataKey];
  if (!bigCategory) return;

  // 如果已经加载过数据，不再重复加载
  if (dropdownData[dataKey] && dropdownData[dataKey].length > 0) return;

  getDropdownData(bigCategory, dataKey);
};

// 编辑企业信息相关
const editCompanyInfoDialogVisible = ref(false);
const editCompanyInfoForm = reactive({
  companyName: "",
  intentionProject: "",
  customerIntentionLevel: "",
  customerSource: "",
  checkInType: "",
  enterpriseAddress: [],
  annualTax: "",
  industry: "",
  investmentPurpose: "",
  resourceCapability: "",
  enterpriseQualification: "",
  employeeCount: "",
  mainBusiness: "",
  focusPoint: "",
  customerId: "",
});

const editCompanyInfoRules = reactive({
  companyName: [
    { required: true, message: "请输入企业名称", trigger: "blur" },
    { pattern: /^\S+$/, message: "企业名称不能包含空格", trigger: "blur" },
    { min: 1, max: 20, message: "企业名称长度不能超过20个字", trigger: "blur" },
  ],
});

const editCompanyInfoFormRef = ref(null);

// 打开编辑弹窗
const handleEditCompanyInfo = () => {
  if (!companyInfo.value.customerId && !companyInfo.value.companyId) {
    ElMessage.error("无法获取客户ID");
    return;
  }

  const customerId = companyInfo.value.customerId || companyInfo.value.companyId;

  selectCompanyTotalByCustomerId(customerId)
    .then((res) => {
      if (res.code === 200 && res.data) {
        // 创建数据副本
        const data = { ...res.data };

        // 将数字转换为客户意向等级选项值
        if (data.customerIntentionLevel) {
          const levelMap = {
            4: "A级 (已缴纳意向金)",
            3: "B级 (1个月内可签约)",
            2: "C级 (3个月内需持续培育)",
            1: "D级 (明确表示无意向)",
          };
          data.customerIntentionLevel =
            levelMap[data.customerIntentionLevel] || data.customerIntentionLevel;
        }

        // 处理地区数据回显
        if (data.enterpriseProvince || data.enterpriseCity || data.enterpriseDistrict) {
          // 根据省市区名称查找对应的编码
          const addressCodes = [];

          // 查找省编码
          if (data.enterpriseProvince) {
            const provinceItem = processedRegionData.find(
              (province) =>
                province.label.includes(data.enterpriseProvince) ||
                data.enterpriseProvince.includes(province.label)
            );
            if (provinceItem) {
              addressCodes.push(provinceItem.value);

              // 查找市编码
              if (data.enterpriseCity) {
                const cityItem = (provinceItem.children || []).find(
                  (city) =>
                    city.label.includes(data.enterpriseCity) ||
                    data.enterpriseCity.includes(city.label)
                );
                if (cityItem) {
                  addressCodes.push(cityItem.value);

                  // 查找区编码
                  if (data.enterpriseDistrict) {
                    const districtItem = (cityItem.children || []).find(
                      (district) =>
                        district.label.includes(data.enterpriseDistrict) ||
                        data.enterpriseDistrict.includes(district.label)
                    );
                    if (districtItem) {
                      addressCodes.push(districtItem.value);
                    }
                  }
                }
              }
            }
          }
          data.enterpriseAddress = addressCodes;
        } else {
          data.enterpriseAddress = [];
        }

        // 填充表单数据
        editCompanyInfoForm.companyName = data.companyName || "";
        editCompanyInfoForm.intentionProject = data.intentionProject || data.zt || "";
        editCompanyInfoForm.customerIntentionLevel = data.customerIntentionLevel || "";
        editCompanyInfoForm.customerSource = data.customerSource || "";
        editCompanyInfoForm.checkInType = data.checkInType || "";
        editCompanyInfoForm.enterpriseAddress = data.enterpriseAddress || [];
        editCompanyInfoForm.annualTax = data.annualTax || "";
        editCompanyInfoForm.industry = data.industryCategory || data.industry || "";
        editCompanyInfoForm.investmentPurpose = data.investmentPurpose || "";
        editCompanyInfoForm.resourceCapability = data.resourceCapability || "";
        editCompanyInfoForm.enterpriseQualification = data.enterpriseQualification || "";
        editCompanyInfoForm.employeeCount = data.employeeCount || "";
        editCompanyInfoForm.mainBusiness = data.mainBusiness || "";
        editCompanyInfoForm.focusPoint = data.focusPoint || "";
        editCompanyInfoForm.customerId = customerId;

        editCompanyInfoDialogVisible.value = true;
      } else {
        ElMessage.error("获取企业信息失败");
      }
    })
    .catch((err) => {
      console.error("获取企业信息失败:", err);
      ElMessage.error("获取企业信息失败");
    });
};

// 关闭编辑弹窗
const handleEditCompanyInfoClose = () => {
  ElMessageBox.confirm("确认放弃修改吗？")
    .then(() => {
      editCompanyInfoDialogVisible.value = false;
      resetEditCompanyInfoForm();
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 重置编辑表单
const resetEditCompanyInfoForm = () => {
  editCompanyInfoFormRef.value.resetFields();
  for (let key in editCompanyInfoForm) {
    if (typeof editCompanyInfoForm[key] === "string") {
      editCompanyInfoForm[key] = "";
    } else if (Array.isArray(editCompanyInfoForm[key])) {
      editCompanyInfoForm[key] = [];
    }
  }
};

// 提交编辑表单
const submitEditCompanyInfoForm = () => {
  editCompanyInfoFormRef.value.validate((valid) => {
    if (valid) {
      const submitData = { ...editCompanyInfoForm };

      // 转换客户意向等级
      if (submitData.customerIntentionLevel === "A级 (已缴纳意向金)") {
        submitData.customerIntentionLevel = 4;
      } else if (submitData.customerIntentionLevel === "B级 (1个月内可签约)") {
        submitData.customerIntentionLevel = 3;
      } else if (submitData.customerIntentionLevel === "C级 (3个月内需持续培育)") {
        submitData.customerIntentionLevel = 2;
      } else if (submitData.customerIntentionLevel === "D级 (明确表示无意向)") {
        submitData.customerIntentionLevel = 1;
      }

      // 处理地址数据 - 将编码转换为名称
      if (submitData.enterpriseAddress && Array.isArray(submitData.enterpriseAddress)) {
        const [provinceCode, cityCode, districtCode] = submitData.enterpriseAddress;

        // 根据编码查找对应的中文名称
        submitData.enterpriseProvince = findRegionName(provinceCode) || "";
        submitData.enterpriseCity = findRegionName(cityCode) || "";
        submitData.enterpriseDistrict = findRegionName(districtCode) || "";
      }

      // 载体与意向项目是一个意思，同步更新
      if (submitData.intentionProject) {
        submitData.zt = submitData.intentionProject;
      }

      updateCustomerInfo(submitData)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("保存成功");
            editCompanyInfoDialogVisible.value = false;
            resetEditCompanyInfoForm();
            // 刷新企业信息
            fetchCompanyInfo();
          } else {
            ElMessage.error(res.msg || "保存失败");
          }
        })
        .catch((err) => {
          console.error("保存失败:", err);
          ElMessage.error("保存失败");
        });
    } else {
      ElMessage.error("请检查输入内容");
    }
  });
};

// 刷新状态
const refreshLoading = ref(false);

// 企业信息
const companyInfo = ref({});
const activeTab_file = ref("1");
// 回款计划相关
const paymentPlans = ref([]);
const groupedPaymentPlans = ref([]);
const activeTab = ref("paymentPlan");
const activeCollapse = ref("");
// 添加回款计划标签页相关数据
const activePlanTab = ref("all"); // 默认选中合同总表
const planQueryParams = reactive({
  isNearly: "", // 用于筛选待续租实体
  isNotEnd: "", // 用于筛选进行中合同
  status: "", // 用于筛选合同状态
});
const plansLoading = ref(false);
const paymentLogData = ref([]);
const logTotal = ref(0);
const logLoading = ref(false);
const logQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});
// 欠费回款计划
const arrearsList = ref([]);
const arrearsTotal = ref(0);
const arrearsLoading = ref(false);
const arrearsQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 文件列表相关
const fileList = ref({});
const previewDialogVisible = ref(false);
const previewFileType = ref("");
const previewFileUrl = ref("");
const previewFileName = ref("");

// 缴费流水相关
const paymentHistoryData = ref([]);
const historyTotal = ref(0);
const historyLoading = ref(false);
const historyQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});
const cancellationQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  companyName: companyInfo.value.companyName,
  companyId: route.query.companyId || "",
});
// 中止流程
const deleteEntryProcessThink = () => {
  ElMessageBox.confirm("确定中止当前流程吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteEntryProcess(companyInfo.value.processId).then((res) => {
        if (res && res.code == 200) {
          proxy.$modal.msgSuccess("中止流程成功");
          fetchCompanyInfo();
        }
      });
    })
    .catch(() => {
      proxy.$modal.msgInfo("已取消中止流程");
    });
};
// Tab控制
const activeTabLog = ref("cancellation");
function handleTabChange(tabName) {
  if (tabName === "cancellation") {
    getCancellationInfoList();
  } else if (tabName === "changeLog") {
    getChangeLogList();
  }
}
const cancellationLogData = ref([]);
const cancellationLogLoading = ref(false);

const cancellationTotal = ref(0);
// 合同终止弹窗
const terminationDialogVisible = ref(false);
const terminationData = ref({
  roomList: [],
  paymentPlans: [],
  contractNumber: "",
});
const terminationLoading = ref(false);

// 退租弹窗
const withdrawalDialogVisible = ref(false);
const withdrawalDialogVisibleCompany = ref(false);
// 缴费相关
const companyId = ref(route.query.companyId);
const planId = ref("");
const showPaymentModal = ref(false);
// 监听tab切换
watch(activeTab, (newVal) => {
  if (newVal === "paymentHistory") {
    fetchPaymentHistory();
    fetchActiveContracts(); // 获取合同列表
  } else if (newVal === "paymentLog") {
    fetchPaymentLog();
  }
});

// 监听 companyId 变化，重新加载数据
watch(
  () => route.query.companyId,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      // companyId 变化时，重置所有数据并重新加载
      console.log("companyId changed:", newId);

      setTimeout(() => {
        companyId.value = newId;
        resetAllData();
        fetchCompanyInfo();
      }, 0);
    }
  },
  { immediate: true } // 初始加载时也执行
);
const getCancellationInfoList = async () => {
  cancellationLogLoading.value = true;
  try {
    cancellationQueryParams.value.companyName = companyInfo.value.companyName;
    const response = await cancellation_infoList(cancellationQueryParams.value);
    cancellationLogData.value = response.rows;
    cancellationTotal.value = response.total;
  } finally {
    cancellationLogLoading.value = false;
  }
};

// 合同变更日志相关数据
const changeLogLoading = ref(false);
const changeLogTotal = ref(0);
const changeLogList = ref([]);

const changeLogQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  companyName: companyInfo.value.companyName || "",

  companyId: route.query.companyId || "",
});
// 获取合同变更日志列表
function getChangeLogList() {
  changeLogLoading.value = true;
  changeLogQueryParams.value.companyName = companyInfo.value.companyName;

  getChangeLog(changeLogQueryParams.value)
    .then((res) => {
      if (res && res.code === 200) {
        changeLogList.value = res.rows || [];
        changeLogTotal.value = res.total || 0;
      } else {
        changeLogList.value = [];
        changeLogTotal.value = 0;
      }
    })
    .catch(() => {
      changeLogList.value = [];
      changeLogTotal.value = 0;
    })
    .finally(() => {
      changeLogLoading.value = false;
    });
}
const handleCancellationPagination = (pagination) => {
  cancellationQueryParams.value.pageNum = pagination.page;
  cancellationQueryParams.value.pageSize = pagination.limit;
  getCancellationInfoList();
};
function handleAmount(plan) {
  planId.value = plan.id;
  showPaymentModal.value = true;
}
function handlePaymentSuccess() {
  // 刷新回款计划列表
  fetchPaymentPlans();
  // 刷新文件列表
  fetchFileList();
  // 刷新缴费流水列表
  fetchPaymentHistory();
  // 刷新回款明细列表
  fetchPaymentLog();
  showPaymentModal.value = false;
}
function handlePaymentClose() {
  // 刷新文件列表
  fetchFileList();
  showPaymentModal.value = false;
}

// 重置所有数据
const resetAllData = () => {
  companyInfo.value = {};
  paymentPlans.value = [];
  groupedPaymentPlans.value = [];
  arrearsList.value = [];
  arrearsTotal.value = 0;
  fileList.value = {};
  paymentHistoryData.value = [];
  historyTotal.value = 0;
  paymentLogData.value = [];
  logTotal.value = 0;
  activeTab.value = "paymentPlan";
  activePlanTab.value = "all";
  activeCollapse.value = "";
};
// 重置合同退租日志搜索条件

// 返回上一页
const goBack = () => {
  router.go(-1);
};
// 获取回款明细
const fetchPaymentLog = async () => {
  if (!companyInfo.value.companyId) return;

  logLoading.value = true;
  try {
    const params = {
      companyId: companyInfo.value.companyId,
      pageNum: logQueryParams.pageNum,
      pageSize: logQueryParams.pageSize,
    };

    const res = await payment_logList(params);
    if (res && res.code == 200) {
      // 防御性处理，确保rows为数组
      let rows = [];
      if (Array.isArray(res.rows)) {
        rows = res.rows;
      } else if (
        res.rows &&
        typeof res.rows === "object" &&
        typeof res.rows.length === "number"
      ) {
        rows = Array.from(res.rows);
      }
      paymentLogData.value = rows;
      logTotal.value = res.total || 0;
    } else {
      paymentLogData.value = [];
      logTotal.value = 0;
    }
  } catch (error) {
    console.error("获取回款明细失败:", error);
    paymentLogData.value = [];
    logTotal.value = 0;
  } finally {
    logLoading.value = false;
  }
};

// 回款明细分页处理
const handleLogPagination = ({ page, limit }) => {
  logQueryParams.pageNum = page;
  logQueryParams.pageSize = limit;
  fetchPaymentLog();
};

// 获取欠费回款计划
const fetchArrearsList = async () => {
  if (!companyInfo.value.companyId) return;

  arrearsLoading.value = true;
  try {
    const params = {
      companyId: companyInfo.value.companyId,
      pageNum: arrearsQueryParams.pageNum,
      pageSize: arrearsQueryParams.pageSize,
    };
    const res = await getArrearsList(params);
    if (res && res.code == 200) {
      arrearsList.value = res.rows || [];
      arrearsTotal.value = res.total || 0;
    } else {
      arrearsList.value = [];
      arrearsTotal.value = 0;
    }
  } catch (error) {
    console.error("获取欠费回款计划失败:", error);
    arrearsList.value = [];
    arrearsTotal.value = 0;
  } finally {
    arrearsLoading.value = false;
  }
};

// 欠费回款计划分页处理
const handleArrearsPagination = ({ page, limit }) => {
  arrearsQueryParams.pageNum = page;
  arrearsQueryParams.pageSize = limit;
  fetchArrearsList();
};

// 获取企业信息
/**
 * 获取企业信息
 * 根据路由参数类型调用不同接口获取企业信息
 */
const handleRefresh = async () => {
  refreshLoading.value = true;
  try {
    await fetchCompanyInfo();
    proxy.$modal.msgSuccess("刷新成功");
  } catch (error) {
    console.error("刷新失败:", error);
  } finally {
    refreshLoading.value = false;
  }
};

const fetchCompanyInfo = async () => {
  try {
    // 根据路由参数获取企业信息
    let res;
    console.log("route.query:", route.query);

    if (route.query.companyId) {
      // 通过companyId获取企业信息
      res = await getCompanyInfo({ companyId: route.query.companyId });
    } else if (route.query.customerCode) {
      // 通过customerCode获取企业信息
      res = await getCompanyInfo({ customerCode: route.query.customerCode });
    } else if (route.query.contractNumber) {
      // 通过contractNumber获取企业信息
      res = await getCompanyInfoByContractNumber({
        contractNumber: route.query.contractNumber,
      });
    } else {
      proxy.$modal.msgWarning("缺少必要的查询参数");
      return;
    }

    if (res && res.code === 200 && (res.data || (res.rows && res.rows.length > 0))) {
      companyInfo.value = res.data || res.rows[0];
      console.log("companyInfo:", companyInfo.value);
      // 获取回款计划和文件列表
      await Promise.allSettled([
        fetchPaymentPlans(),
        fetchFileList(),
        fetchPaymentHistory(),
        fetchPaymentLog(),
        fetchArrearsList(),
        getCancellationInfoList(),
      ]);
    } else {
      proxy.$modal.msgError(res.msg || "获取企业信息失败");
    }
  } catch (error) {
    console.error("获取企业信息失败:", error);
  }
};

// 获取回款计划
/**
 * 获取回款计划
 * 根据企业customerCode获取回款计划列表
 */

const fetchPaymentPlans = async () => {
  if (!companyInfo.value.companyId) return;
  try {
    const res = await DraftContractList({
      ...planQueryParams,
      customerCode: companyInfo.value.companyId,
      companyId: companyInfo.value.companyId,
      pageNum: 1,
      pageSize: 100,
    });
    if (res && res.code === 200) {
      paymentPlans.value = res.rows || [];
    } else {
      paymentPlans.value = [];
      proxy.$modal.msgError(res.msg || "获取合同数据失败");
    }
  } catch (error) {
    console.error("获取合同数据失败:", error);
    paymentPlans.value = [];
  } finally {
  }
};

// 待续租实体合同列表相关
const nearlyPaymentPlans = ref([]);
const nearlyLoading = ref(false);

// 当前选中的合同（单选）
const selectedContract = ref(null);
const selectedContractPlans = ref([]);

// 退租表单
const withdrawalFormRef = ref(null);
const withdrawalForm = reactive({
  cancellationer: "",
  cancellationReason: "",
  cancellationRemake: "",
});

const withdrawalFormRules = {
  cancellationer: [{ required: true, message: "请选择退租方", trigger: "change" }],
  cancellationReason: [{ required: true, message: "请输入退租原因", trigger: "blur" }],
};

// 处理合同单选选择
const handleContractSelectionChange = (row) => {
  // row 为被选择的合同对象
  selectedContract.value = row || null;
  // 更新选中合同的回款计划显示
  if (selectedContract.value) {
    selectedContractPlans.value = selectedContract.value.paymentPlanList || [];
  } else {
    selectedContractPlans.value = [];
  }
};

// 重置退租表单
const resetWithdrawalForm = () => {
  if (withdrawalFormRef.value && withdrawalFormRef.value.resetFields) {
    try {
      withdrawalFormRef.value.resetFields();
    } catch (e) {
      // ignore
    }
  }
  withdrawalForm.cancellationer = "";
  withdrawalForm.cancellationReason = "";
  withdrawalForm.cancellationRemake = "";
  selectedContract.value = null;
  selectedContractPlans.value = [];
};

// 监听退租弹窗关闭时重置表单与选中项
watch(withdrawalDialogVisible, (visible) => {
  if (!visible) {
    resetWithdrawalForm();
  }
});
watch(withdrawalDialogVisibleCompany, (visible) => {
  if (!visible) {
    resetWithdrawalForm();
  }
});

// 获取待续租实体合同列表
const fetchNearlyPaymentPlans = async () => {
  if (!companyInfo.value.companyId) return;
  try {
    const res = await DraftContractList({
      customerCode: companyInfo.value.companyId,
      companyId: companyInfo.value.companyId,
      pageNum: 1,
      pageSize: 100,
      isNotEnd: 1,
      type: "实体",
    });
    if (res && res.code === 200) {
      nearlyPaymentPlans.value = res.rows || [];
    } else {
      nearlyPaymentPlans.value = [];
      proxy.$modal.msgError(res.msg || "获取合同数据失败");
    }
  } catch (error) {
    nearlyPaymentPlans.value = [];
    console.error("获取合同数据失败:", error);
  } finally {
  }
};
// 获取文件列表
/**
 * 获取文件列表
 * 根据企业入驻方式和状态获取相关文件
 */
const fetchFileList = async () => {
  fileList.value = {};

  // 检查必要参数
  if (!companyInfo.value.companyId) {
    console.warn("缺少companyId，无法获取文件列表");
    return;
  }

  try {
    // 根据入驻方式和状态确定需要获取的文件标签
    let tags = [];

    if (companyInfo.value.entryMode === "挂靠") {
      // 挂靠入驻企业
      if (companyInfo.value.status >= 1) {
        // 备案环节及之后的文件
        tags.push(
          { tag: 0, name: "record" }, // 备案表
          { tag: 2, name: "sign" }, // 法人签字笔迹
          { tag: 3, name: "id" }, // 自然人身份证
          { tag: 4, name: "license" } // 非自然人营业执照
        );

        // 非迁址企业需要信息注册表
        if (companyInfo.value.companyClass !== "迁址") {
          tags.push({ tag: 1, name: "info" });
        }
      }

      if (companyInfo.value.status >= 2) {
        // 合同环节及之后的文件
        tags.push({ tag: 14, name: "virtualArchive" }); // 挂靠合同归档文件
      }

      if (companyInfo.value.status >= 3) {
        // 办证环节的文件
        tags.push(
          { tag: 2, name: "sign" }, // 法人签字笔迹
          { tag: 3, name: "id" }, // 自然人身份证
          { tag: 4, name: "license" }, // 非自然人营业执照
          { tag: 12, name: "licensePdf" } // 营业执照
        );
      }
    } else {
      // 实体入驻企业
      if (companyInfo.value.status >= 1) {
        // 备案环节及之后的文件
        tags.push(
          { tag: 0, name: "record" }, // 备案表
          { tag: 2, name: "sign" }, // 法人签字笔迹
          { tag: 3, name: "id" }, // 自然人身份证
          { tag: 4, name: "license" } // 非自然人营业执照
        );

        // 非迁址企业需要信息注册表
        if (companyInfo.value.companyClass !== "迁址") {
          tags.push({ tag: 1, name: "info" });
        }
      }

      if (companyInfo.value.status >= 2) {
        // 合同环节及之后的文件
        tags.push(
          { tag: 7, name: "contractArchive" }, // 实体合同归档文件
          { tag: 14, name: "virtualArchive" } // 挂靠合同归档文件
        );
      }

      if (companyInfo.value.status >= 3) {
        // 办证环节的文件
        tags.push(
          { tag: 15, name: "beforeDecoration" }, // 入驻前图片
          { tag: 16, name: "afterDecoration" }, // 入驻后图片
          { tag: 9, name: "propertyHandover" }, // 物业交接单
          { tag: 11, name: "planPdf" }, // 平面图(PDF)
          { tag: 19, name: "planZip" }, // 平面图(ZIP)
          { tag: 17, name: "waterMeter" }, // 水表
          { tag: 18, name: "electricMeter" }, // 电表
          { tag: 12, name: "licensePdf" } // 营业执照
        );
      }
    }

    // 去重处理
    const uniqueTags = [];
    const tagSet = new Set();
    tags.forEach((tagObj) => {
      if (!tagSet.has(tagObj.tag)) {
        tagSet.add(tagObj.tag);
        uniqueTags.push(tagObj);
      }
    });

    // 获取所有文件
    const filePromises = uniqueTags.map((tagObj) =>
      getFileByCompanyIdAndTag({
        companyId: companyInfo.value.companyId,
        tag: tagObj.tag,
        pageNum: 1,
        pageSize: 100,
      }).catch((error) => {
        console.error(`获取标签${tagObj.tag}的文件失败:`, error);
        return null;
      })
    );

    const results = await Promise.allSettled(filePromises);

    results.forEach((result, index) => {
      if (
        result.status === "fulfilled" &&
        result.value &&
        result.value.code === 200 &&
        result.value.rows
      ) {
        fileList.value[uniqueTags[index].name] = result.value.rows;
      }
    });
  } catch (error) {
    console.error("获取文件列表失败:", error);
    fileList.value = {};
  }
};

// 缴费流水表单相关
const paymentHistoryDialogVisible = ref(false);
const paymentHistoryForm = reactive({
  id: null,
  companyId: companyInfo.value.companyId,
  amount: 0,
  remainingAmount: 0,
  contractNumber: "",
  paidAmount: 0,
  status: 0,
});
const paymentHistoryFormRef = ref();

// 缴费流水表单验证规则
const paymentHistoryRules = {
  amount: [{ required: true, message: "请输入总金额", trigger: "blur" }],
  remainingAmount: [{ required: true, message: "请输入剩余金额", trigger: "blur" }],
  paidAmount: [{ required: true, message: "请输入已付金额", trigger: "blur" }],
  contractNumber: [{ required: true, message: "请输入合同编号", trigger: "blur" }],
};

// 获取缴费流水
const fetchPaymentHistory = async () => {
  if (!companyInfo.value.companyId) return;

  historyLoading.value = true;
  try {
    const params = {
      companyId: companyInfo.value.companyId,
      pageNum: historyQueryParams.pageNum,
      pageSize: historyQueryParams.pageSize,
    };

    const res = await getPaymentHistoryList(params);
    if (res && res.code == 200) {
      // 防御性处理，确保rows为数组
      let rows = [];
      if (Array.isArray(res.rows)) {
        rows = res.rows;
      } else if (
        res.rows &&
        typeof res.rows === "object" &&
        typeof res.rows.length === "number"
      ) {
        rows = Array.from(res.rows);
      }
      paymentHistoryData.value = rows;
      historyTotal.value = res.total || 0;
    } else {
      paymentHistoryData.value = [];
      historyTotal.value = 0;
    }
  } catch (error) {
    console.error("获取缴费流水失败:", error);
    paymentHistoryData.value = [];
    historyTotal.value = 0;
  } finally {
    historyLoading.value = false;
  }
};

// 新增缴费流水
const handleAddPaymentHistory = () => {
  resetPaymentHistoryForm();
  paymentHistoryForm.companyId = companyInfo.value.companyId;
  paymentHistoryForm.companyName = companyInfo.value.companyName;
  paymentHistoryDialogVisible.value = true;
};

// 修改缴费流水
const handleEditPaymentHistory = (row) => {
  resetPaymentHistoryForm();
  Object.assign(paymentHistoryForm, row, {
    companyId: companyInfo.value.companyId,
  });
  paymentHistoryDialogVisible.value = true;
};

// 删除缴费流水
const handleDeletePaymentHistory = async (row) => {
  try {
    await proxy.$modal.confirm("确定要删除该缴费流水吗？");

    // 这里需要调用删除接口，根据实际API调整
    // 假设有一个deletePaymentHistory API，参数包含id和flag
    const deleteParams = {
      id: row.id,
      flag: 1,
    };

    // 删除操作示例（需要根据实际API调整）
    await deletePaymentHistory(row.id);

    proxy.$modal.msgSuccess("删除成功");
    fetchPaymentHistory(); // 重新加载数据
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除缴费流水失败:", error);
    }
  }
};

// 重置缴费流水表单
const resetPaymentHistoryForm = () => {
  // paymentHistoryFormRef.value.resetFields();
  paymentHistoryForm.id = null;
  paymentHistoryForm.companyId = companyInfo.value.companyId;
  paymentHistoryForm.amount = 0;
  paymentHistoryForm.companyName = "";
  paymentHistoryForm.remainingAmount = 0;
  paymentHistoryForm.contractNumber = "";
  paymentHistoryForm.paidAmount = 0;
  paymentHistoryForm.status = 0;
};

// 提交缴费流水表单
const submitPaymentHistoryForm = () => {
  paymentHistoryFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      paymentHistoryForm.remainingAmount = paymentHistoryForm.amount;
      // 根据是否有id判断是新增还是修改
      if (paymentHistoryForm.id) {
        // 修改操作示例（需要根据实际API调整）
        await updatePaymentHistory(paymentHistoryForm);
      } else {
        // 新增操作示例（需要根据实际API调整）
        await insertPaymentHistory(paymentHistoryForm);
      }

      proxy.$modal.msgSuccess(paymentHistoryForm.id ? "修改成功" : "新增成功");
      paymentHistoryDialogVisible.value = false;
      fetchPaymentHistory(); // 重新加载数据
    } catch (error) {
      console.error("提交缴费流水表单失败:", error);
    }
  });
}; // 分页处理
const handleHistoryPagination = ({ page, limit }) => {
  historyQueryParams.pageNum = page;
  historyQueryParams.pageSize = limit;
  fetchPaymentHistory();
};

// 预览文件
const previewFile = (file) => {
  console.log("file", file);
  previewFileUrl.value = file.url;
  previewFileName.value = file.fileName;

  // 判断文件类型
  const fileName = file.url || "";
  const ext = fileName.split(".").pop().toLowerCase();

  if (["jpg", "jpeg", "png", "gif", "bmp", "webp"].includes(ext)) {
    previewFileType.value = "image";
  } else if (ext === "pdf") {
    previewFileType.value = "pdf";
  } else if (["doc", "docx"].includes(ext)) {
    previewFileType.value = "word";
  } else if (["xls", "xlsx"].includes(ext)) {
    previewFileType.value = "excel";
  } else if (["ppt", "pptx"].includes(ext)) {
    previewFileType.value = "ppt";
  } else if (["txt"].includes(ext)) {
    previewFileType.value = "txt";
  } else if (["zip", "rar", "7z"].includes(ext)) {
    previewFileType.value = "archive";
  } else {
    previewFileType.value = "other";
  }

  previewDialogVisible.value = true;
};

// 为表格展示准备的数据
const groupedPaymentPlansForTable = computed(() => {
  return groupedPaymentPlans.value;
});

/**
 * 处理回款计划标签页切换
 * @param {String} tabName - 标签页名称
 */
const handlePlanTabChange = (tabName) => {
  // 根据标签页设置参数
  if (tabName === "nearly") {
    planQueryParams.isNearly = true;
    planQueryParams.type = "实体";

    planQueryParams.isNotEnd = "";
    planQueryParams.status = "";
  } else if (tabName === "notEnd") {
    planQueryParams.isNotEnd = 1;
    planQueryParams.isNearly = "";
    planQueryParams.status = "";
    planQueryParams.type = null;
  } else if (tabName === "discarded") {
    // 退用合同，设置status为3（已退用）
    planQueryParams.status = 3;
    planQueryParams.isNotEnd = "";
    planQueryParams.isNearly = "";
    planQueryParams.type = null;
  } else if (tabName === "finished") {
    // 完结合同，设置status为1（已完结）
    planQueryParams.status = 1;
    planQueryParams.isNotEnd = "";
    planQueryParams.isNearly = "";
    planQueryParams.type = null;
  } else if (tabName === "toBeDiscarded") {
    // 待退用合同，设置status为2（待退用）
    planQueryParams.status = 2;
    planQueryParams.isNotEnd = "";
    planQueryParams.isNearly = "";
    planQueryParams.type = null;
  } else {
    planQueryParams.isNearly = "";
    planQueryParams.isNotEnd = "";
    planQueryParams.status = "";
    planQueryParams.type = null;
  }

  // 重新获取数据
  fetchPaymentPlans();
};

// 合同终止处理
const handleTerminateContract = async (contractNumber) => {
  try {
    await proxy.$modal.confirm(`是否确认终止合同 ${contractNumber}？`);
    terminationLoading.value = true;
    terminationDialogVisible.value = true;
    terminationData.value.contractNumber = contractNumber;

    const res = await getCompanyInfoByContractNumber({ contractNumber });
    if (res && res.code === 200 && res.data) {
      const companyData = res.data;
      terminationData.value.roomList = companyData.roomList || [];
      // 筛选指定合同下，剩余金额大于0的回款计划
      terminationData.value.paymentPlans = (paymentPlans.value || []).filter(
        (plan) => plan.contractNumber === contractNumber && plan.remainingAmount > 0
      );
    } else {
      proxy.$modal.msgError("获取合同信息失败");
      terminationDialogVisible.value = false;
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("合同终止操作失败:", error);
    }
  } finally {
    terminationLoading.value = false;
  }
};
// 违约押金处理

const handleDefaultDeposit = async () => {
  if (!selectedContract.value) {
    proxy.$modal.msgWarning("请选择要转租期的合同");
    return;
  }

  try {
    // 表单验证
    await withdrawalFormRef.value.validate();
  } catch (error) {
    console.warn("表单验证失败:", error);
    return;
  }

  try {
    await proxy.$modal.confirm(
      `确定要对合同 ${selectedContract.value.contractNumber} 进行押金转违约金吗？`
    );

    // 准备提交数据
    const submitData = {
      contractNumber: selectedContract.value.contractNumber,
      cancellationer: withdrawalForm.cancellationer,
      cancellationReason: withdrawalForm.cancellationReason,
      cancellationRemake: withdrawalForm.cancellationRemake,
    };

    // 调用押金转租期接口
    const res = await defaultDeposit(submitData);

    if (res && res.code === 200) {
      proxy.$modal.msgSuccess("押金转违约金成功");
      withdrawalDialogVisible.value = false;
      withdrawalDialogVisibleCompany.value = false;
      resetWithdrawalForm(); // 重置表单
      // 刷新数据
      fetchPaymentPlans();
    } else {
      proxy.$modal.msgError(res.msg || "押金转违约金失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("押金转违约金失败:", error);
    }
  }
};

// 押金转租期处理
const handleDepositToRent = async () => {
  if (!selectedContract.value) {
    proxy.$modal.msgWarning("请选择要转租期的合同");
    return;
  }

  try {
    // 表单验证
    await withdrawalFormRef.value.validate();
  } catch (error) {
    console.warn("表单验证失败:", error);
    return;
  }

  try {
    await proxy.$modal.confirm(
      `确定要对合同 ${selectedContract.value.contractNumber} 进行押金转租期吗？`
    );

    // 准备提交数据
    const submitData = {
      contractNumber: selectedContract.value.contractNumber,
      cancellationer: withdrawalForm.cancellationer,
      cancellationReason: withdrawalForm.cancellationReason,
      cancellationRemake: withdrawalForm.cancellationRemake,
    };

    // 调用押金转租期接口
    const res = await transferDepositToRent(submitData);

    if (res && res.code === 200) {
      proxy.$modal.msgSuccess("押金转租期成功");
      withdrawalDialogVisible.value = false;
      withdrawalDialogVisibleCompany.value = false;
      resetWithdrawalForm(); // 重置表单
      // 刷新数据
      fetchPaymentPlans();
    } else {
      proxy.$modal.msgError(res.msg || "押金转租期失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("押金转租期失败:", error);
    }
  }
};

// 押金退费处理
const handleDepositRefund = async () => {
  if (!selectedContract.value) {
    proxy.$modal.msgWarning("请选择要退费的合同");
    return;
  }

  try {
    await withdrawalFormRef.value.validate();
  } catch (error) {
    console.warn("表单验证失败:", error);
    return;
  }

  try {
    await proxy.$modal.confirm(
      `确定要对合同 ${selectedContract.value.contractNumber} 进行押金退费吗？`
    );

    const submitData = {
      contractNumber: selectedContract.value.contractNumber,
      cancellationer: withdrawalForm.cancellationer,
      cancellationReason: withdrawalForm.cancellationReason,
      cancellationRemake: withdrawalForm.cancellationRemake,
    };

    const res = await depositRefund(submitData);
    if (res && res.code === 200) {
      proxy.$modal.msgSuccess("押金退费成功");
      withdrawalDialogVisible.value = false;
      withdrawalDialogVisibleCompany.value = false;
      resetWithdrawalForm();
      fetchPaymentPlans();
    } else {
      proxy.$modal.msgError(res.msg || "押金退费失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("押金退费失败:", error);
    }
  }
};

// 押金转租期（合同终止）
const handleDepositToRentTermination = async () => {
  const contractNumber = terminationData.value.contractNumber;
  if (!contractNumber) {
    proxy.$modal.msgWarning("缺少合同编号");
    return;
  }

  try {
    terminationLoading.value = true;
    // 1. 调用押金转租期接口
    await transferDepositToRent(contractNumber);
    proxy.$modal.msgSuccess("押金转租期成功");

    // 2. 调用释放房源接口
    await unbindRoom({ contractNumber });
    proxy.$modal.msgSuccess("房源已释放");

    // 3. 关闭弹窗并刷新数据
    terminationDialogVisible.value = false;
    fetchPaymentPlans(); // 刷新回款计划
  } catch (error) {
    console.error("押金转租期操作失败:", error);
  } finally {
    terminationLoading.value = false;
  }
};

// 添加获取进行中合同列表的方法
const fetchActiveContracts = async () => {
  // 检查必要参数
  if (!companyInfo.value.companyId) {
    console.warn("缺少companyId，无法获取合同列表");
    return;
  }

  contractListLoading.value = true;
  try {
    const params = {
      companyId: companyInfo.value.companyId,
      isNotEnd: 1,
      type: "实体", // 只获取实体合同
      pageNum: 1,
      pageSize: 100,
    };

    const res = await DraftContractList(params);
    if (res && res.code === 200) {
      contractList.value = Array.isArray(res.rows) ? res.rows : [];
    } else {
      contractList.value = [];
      proxy.$modal.msgError(res.msg || "获取合同列表失败");
    }
  } catch (error) {
    console.error("获取合同列表失败:", error);
    contractList.value = [];
  } finally {
    contractListLoading.value = false;
  }
};

/**
 * 处理退用合同开关切换事件
 * @param {Boolean} val - 开关状态
 */
// const handleAbandonContractChange = (val) => {
//   if (val) {
//     // 如果打开退用合同开关，则获取合同列表
//     fetchActiveContracts();
//   } else {
//     // 如果关闭退用合同开关，则清空选择
//     contractForm.selectedContract = "";
//     contractList.value = [];
//   }
// };
// 合同变更
const handleChange = () => {
  contractForm.actionType = "合同变更";
  contractDialogVisible.value = true;
  fetchActiveContracts();
};
const handleChangeBtn = async (row) => {
  contractForm.actionType = "合同变更";
  contractDialogVisible.value = true;
  await fetchActiveContracts();
  await setTimeout(() => {
    contractForm.selectedContract = row.contractNumber;
  }, 100);
};
/**
 * 扩租处理函数
 */
const handleExpansion = () => {
  contractForm.actionType = "expansion";
  contractDialogVisible.value = true;
  fetchActiveContracts();
};

/**
 * 缩租处理函数
 */
const handleReduction = () => {
  contractForm.actionType = "reduction";
  contractDialogVisible.value = true;
  fetchActiveContracts();
};

/**
 * 续租处理函数
 */
const handleRenewal = () => {
  contractForm.actionType = "renewal";
  contractDialogVisible.value = true;
  fetchActiveContracts();
};
const activeContracts = ref([]);
/**
 * 退租处理函数
 */
const handleWithdrawal = () => {
  // withdrawalDialogVisible.value = true;
  withdrawalDialogVisibleCompany.value = true;
  fetchArrearsList();
  fetchNearlyPaymentPlans(); // 获取待续租实体合同列表
};
const handleWithdrawalBtn = async (row) => {
  withdrawalDialogVisible.value = true;
  // withdrawalDialogVisibleCompany.value = true;
  await fetchArrearsList();
  await fetchNearlyPaymentPlans(); // 获取待续租实体合同列表
  await setTimeout(() => {
    console.log("row.contractNumber", row.contractNumber);
    contractForm.selectedContract = row.contractNumber;
  }, 100);
};
const contractFormRef = ref();
/**
 * 合同操作提交处理函数
 */
const handleContractSubmit = async () => {
  try {
    // 表单验证
    await contractFormRef.value.validate();
  } catch (error) {
    console.warn("表单验证失败:", error);
    return;
  }

  // 检查是否选择了合同
  if (!contractForm.selectedContract) {
    proxy.$modal.msgWarning("请选择需变更的合同");
    return;
  }

  // 变更前校验选中合同是否有欠费
  // try {
  //   const res = await getArrearsList({
  //     contractNumber: contractForm.selectedContract,
  //     pageNum: 1,
  //     pageSize: 100,
  //   });
  //   if (res && res.rows && res.rows.length > 0) {
  //     proxy.$modal.msgWarning("当前选中合同仍有欠费，请先处理欠费后再变更！");
  //     return;
  //   }
  // } catch (e) {
  //   proxy.$modal.msgError("校验欠费失败，请重试");
  //   return;
  // }

  try {
    // 检查是否需要调用退用合同接口
    if (contractForm.isAbandonOriginalContract) {
      // 调用退用合同接口，传入选中的合同编号
      await DraftContract(contractForm.selectedContract);
      proxy.$modal.msgSuccess("原合同已退用");
    }
  } catch (error) {
    console.error("退用合同失败:", error);
    return;
  }
  // 准备提交数据
  const submitData = {
    companyId: companyInfo.value.companyId,
    actionType: contractForm.actionType,
    isAbandonOriginalContract: contractForm.isAbandonOriginalContract ? 1 : 0,
    isRehandleCertificate: contractForm.isRehandleCertificate ? 1 : 0,
    status: 5,
    contractNumber: contractForm.selectedContract || "",
  };

  try {
    // 调用主接口
    submitData.type =
      submitData.actionType == "expansion"
        ? 2
        : submitData.actionType == "reduction"
        ? 3
        : submitData.actionType == "renewal"
        ? 4
        : 5;
    await insertEntryProcess(submitData).then((res) => {
      if (res && res.code == 200) {
        companyInfo.value.processId = res.data.id;
        // 如果勾选了重新办证，添加办证相关信息
        if (contractForm.isRehandleCertificate) {
          insertCertification({
            companyId: companyInfo.value.companyId,
            processId: res.data.id,
          });
        }
      } else {
        throw new Error(res.msg || "操作失败");
      }
    });

    // 显示成功消息
    proxy.$modal.msgSuccess("操作成功");

    // 关闭对话框
    contractDialogVisible.value = false;

    // 跳转到ContractEntry路由
    router.push({
      name: "ContractEntry",
      query: {
        companyId: companyInfo.value.companyId,
        actionType: contractForm.actionType,
        isAbandonOriginalContract: contractForm.isAbandonOriginalContract ? 1 : 0,
        isRehandleCertificate: contractForm.isRehandleCertificate ? 1 : 0,
        processId: companyInfo.value.processId,
        processType: companyInfo.value.processType,
        certificationType: contractForm.certificationType,
        certificationPersonnel: contractForm.certificationPersonnel,
        carrieType: companyInfo.value.carrieType || "",
      },
    });
  } catch (error) {
    console.error("提交操作失败:", error);
  }
};

const contractDialogVisible = ref(false);
const contractForm = reactive({
  isAbandonOriginalContract: false,
  isRehandleCertificate: false,
  actionType: "合同变更", // 'expansion' | 'reduction' | 'renewal'
  certificationType: "",
  certificationPersonnel: "",
  selectedContract: "", // 添加选中的合同编号
});
// 添加表单验证规则
const contractFormRules = {
  certificationType: [
    {
      required: true,
      message: "请选择办证方式",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (contractForm.isRehandleCertificate && !value) {
          callback(new Error("请选择办证方式"));
        } else {
          callback();
        }
      },
    },
  ],
  selectedContract: [
    {
      required: true,
      message: "请选择要退用的合同",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (contractForm.isAbandonOriginalContract && !value) {
          callback(new Error("请选择要退用的合同"));
        } else {
          callback();
        }
      },
    },
  ],
};
// 添加合同列表相关数据
const contractList = ref([]);
const contractListLoading = ref(false);
const handleContractEntry = async () => {
  await selectById(companyInfo.value.processId).then((res) => {
    router.push({
      name: "ContractEntry",
      query: {
        companyId: companyInfo.value.companyId,
        // type: res.data.type,
        isAbandonOriginalContract: res.data.isAbandonOriginalContract,
        isRehandleCertificate: res.data.isRehandleCertificate,
        processId: companyInfo.value.processId,
        processType: companyInfo.value.processType,
        carrieType: res.data.carrieType || "",
        carrierName: res.data.zt || "",
      },
    });
  });
};
onMounted(() => {
  console.log("mounted");
  fetchCompanyInfo();
});
</script>

<style scoped>
.look-company-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.company-info-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #303133;
}

.operation-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.operation-buttons .el-button {
  border-radius: 20px;
}

.plan-tabs {
  margin-bottom: 20px;
}

.plan-list-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.collapse-title {
  display: flex;
  align-items: center;
  font-weight: bold;
  color: #409eff;
  padding: 10px 0;
}

.plan-count {
  margin: 0 50px;
  font-size: 14px;
  color: #909399;
}

.plan-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.plan-item:last-child {
  border-bottom: none;
}

.plan-row {
  display: flex;
  align-items: center;
}

.plan-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.plan-value {
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-section {
  margin-top: 20px;
}

.file-group {
  margin-bottom: 20px;
}

.file-label {
  font-weight: bold;
  margin-bottom: 10px;
  color: #666;
  font-size: 16px;
}

.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.file-tag {
  cursor: pointer;
  margin-bottom: 5px;
}

.record-container {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.add-payment-btn {
  margin-bottom: 20px;
}

.payment-history-form {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 6px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.payment-history-table {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.file-preview-dialog :deep(.el-dialog__body) {
  padding: 10px;
}

/* 只读模式下隐藏所有按钮，但保留刷新按钮 */
.look-company-container.readonly :deep(.el-button:not(.refresh-btn)) {
  display: none !important;
}
/* 确保刷新按钮在只读模式下仍然显示 */
.look-company-container.readonly :deep(.refresh-btn) {
  display: inline-flex !important;
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.pdf-preview-container,
.office-preview-container,
.txt-preview-container {
  min-height: 60vh;
}

.preview-iframe {
  width: 100%;
  height: 60vh;
  border: none;
}

.preview-alert {
  margin-top: 20px;
}

.preview-tip {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 0;
}

.contract-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.contract-form {
  padding: 10px 0;
}

.certification-section {
  padding: 15px;
  border-radius: 6px;
  margin-top: 15px;
}

.form-item-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.record-tabs :deep(.el-tabs__content) {
  padding: 20px 0;
}
:deep(.el-card__header) {
  border-bottom: 1px solid #ebeef5;
}
</style>
